package com.vinoxm.admin.service;

import com.vinoxm.admin.dao.AuthUserDao;
import com.vinoxm.admin.model.AuthUser;
import com.vinoxm.admin.vo.UserVo;
import com.vinoxm.common.core.service.BaseService;
import lombok.extern.log4j.Log4j2;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component("authUserService")
@Log4j2
public class AuthUserService extends BaseService<AuthUserDao> implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("username: " + username);
        AuthUser user = baseDao.selByUname(username);
        if (user == null) {
            throw new UsernameNotFoundException(String.format("user:%s not found!", username));
        } else {
            String role = "ROLE_ADMIN";
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority(role));
            UserVo.ExtraData extraData = new UserVo.ExtraData();
            extraData.setPassword(user.getPassword());
            return new UserVo(username, user.getPassword(), authorities,user.getUserId(), extraData);
        }
    }
}
